# -*- encoding:utf-8

"""
a gui for unvpk
able to pick multiple file or folder into the list
"""

from PyQt4.QtGui import *
from PyQt4.QtCore import *

import os.path
import sys
import time
import logging
import unvpk


logging.basicConfig(level=logging.DEBUG)


class UnpackTasks(QThread):
    progressChanged = pyqtSignal()
    def __init__(self, vpks, use_origin, path, rename):
        super().__init__()
        self.vpks = vpks
        self.use_origin = use_origin
        self.path = path
        self.rename = rename
        self.running = True
        self.progress = 0.0
        self.taskidx = 0
        self.progresstotal = 0.0
        self.unpacker = unvpk.Unpacker()

    def run(self):
        for i, vpk in enumerate(self.vpks):
            if self.running:
                self.taskidx = i
                self.unpack(vpk)
                while self.unpacker.isRunning():
                    self.progress = self.unpacker.progress
                    self.progresstotal = (self.progress + self.taskidx)/len(self.vpks)
                    self.progressChanged.emit()

                    time.sleep(0.5)

    def unpack(self, vpk):
        path, name = os.path.split(vpk)
        if not self.use_origin and self.path:
            path = self.path

        path = os.path.join(path, name[0:-4])

        logging.debug(vpk)
        logging.debug(path)
        self.unpacker.settask(vpk, path, self.rename)
        self.unpacker.start()
        #unvpk.unpack(vpk, None, self.rename)

    def stop(self):
        self.running = False




class UnvpkGui(QWidget):
    def __init__(self, parent=None):
        super().__init__(parent=parent)
        self.unpacktasks = None
        self.init_gui()
        self.init_logic()
        self.notrunning()

    def init_gui(self):
        vbox = QVBoxLayout()
        self.tasklist = TaskList()

        vbox.addWidget(self.tasklist)

        self.param = QWidget()
        paramhbox = QHBoxLayout()
        self.lnkRename = QCheckBox('将lnk文件改名')
        paramhbox.addWidget(self.lnkRename)
        self.param.setLayout(paramhbox)
        vbox.addWidget(self.param)

        self.address = Address()
        vbox.addWidget(self.address)

        hbox = QHBoxLayout()
        self.go = QPushButton('处理')
        self.stop = QPushButton('中止')
        hbox.addWidget(self.go)
        hbox.addWidget(self.stop)

        vbox.addLayout(hbox)

        self.progressbar = QProgressBar()
        self.progressbartotal = QProgressBar()
        vbox.addWidget(self.progressbar)
        vbox.addWidget(self.progressbartotal)
        self.setLayout(vbox)

    def update_progressbar(self):
        logging.debug(self.unpacktasks)
        if self.unpacktasks is not None:
            if self.unpacktasks.isRunning():
                self.progressbar.setValue(self.unpacktasks.progress*100)
                self.progressbartotal.setValue(self.unpacktasks.progresstotal*100)
                logging.debug(self.unpacktasks.progress)
            else:
                self.progressbar.setValue(100)
                self.progressbartotal.setValue(100)
        else:
            self.progressbar.setValue(0)
            self.progressbartotal.setValue(0)


    def init_logic(self):
        self.connect(self.go, SIGNAL('clicked()'), self.runtasks)
        self.connect(self.stop, SIGNAL('clicked()'), self.stoptasks)
        if self.unpacktasks is not None:
            self.connect(self.unpacktasks, SIGNAL('finished()'), self.notrunning)
            self.unpacktasks.progressChanged.connect(self.update_progressbar)
            #self.connect(self.unpacktasks, self.unpacktasks.progressChanged, self.update_progressbar())

    def runtasks(self):
        logging.debug(self.tasklist.strlist)
        tasklist = self.tasklist.strlist
        self.unpacktasks = UnpackTasks(tasklist, self.address.use_origin, self.address.path, self.lnkRename.isChecked())
        self.init_logic()
        self.unpacktasks.start()
        self.whilerunning()

    def stoptasks(self):
        if self.unpacktasks is not None and self.unpacktasks.isRunning():
            self.unpacktasks.stop()
        self.notrunning()

    def whilerunning(self):
        self.address.setDisabled(True)
        self.tasklist.setDisabled(True)
        self.param.setDisabled(True)
        self.go.setDisabled(True)
        self.stop.setEnabled(True)

    def notrunning(self):
        self.address.setEnabled(True)
        self.tasklist.setEnabled(True)
        self.param.setEnabled(True)
        self.go.setEnabled(True)
        self.stop.setDisabled(True)
        self.update_progressbar()



class TaskList(QWidget):
    def __init__(self, parent=None):
        super().__init__(parent=parent)
        self.init_gui()
        self.init_logic()
        self.strlist = []

    def init_gui(self):
        vbox = QVBoxLayout()
        self.vpklist = QListWidget()
        vbox.addWidget(self.vpklist)

        bar = QHBoxLayout()
        self.addVpk = QPushButton('添加')
        self.removeVpk = QPushButton('删除')
        self.emptyList = QPushButton('清空')
        bar.addWidget(self.addVpk)
        bar.addWidget(self.removeVpk)
        bar.addWidget(self.emptyList)
        vbox.addLayout(bar)
        self.setLayout(vbox)

    def init_logic(self):
        self.connect(self.addVpk, SIGNAL('clicked()'), self.add)
        self.connect(self.removeVpk, SIGNAL('clicked()'), self.remove)
        self.connect(self.emptyList, SIGNAL('clicked()'), self.empty)

    def add(self):
        vpks = QFileDialog.getOpenFileNames(None, '打开vpk文件', '', 'VPK文件(*.vpk)', QFileDialog.DontUseNativeDialog)
        for vpk in vpks:
            self.tryadd(vpk)
        logging.debug(self.strlist)

    def tryadd(self, vpk):
        if vpk not in self.strlist:
            self.vpklist.addItem(QListWidgetItem(vpk))
            self.strlist.append(vpk)

    def remove(self):
        items = self.vpklist.selectedItems()
        for item in items:
            row = self.vpklist.row(item)
            logging.debug(row)
            if row >= 0:
                self.vpklist.takeItem(row)
                self.strlist.remove(self.strlist[row])
        logging.debug(self.strlist)

    def empty(self):
        self.vpklist.clear()
        self.strlist.clear()
        logging.debug(self.strlist)

class Address(QWidget):
    def __init__(self, parent=None):
        super().__init__(parent=parent)
        self.init_gui()
        self.init_logic()
        self.path = None
        self.use_origin = False


    def init_gui(self):
        self.edit = QLineEdit()
        self.browse = QPushButton('浏览')
        self.originfolder = QCheckBox('输出到源文件目录')
        grid = QGridLayout()
        grid.addWidget(self.originfolder, 0, 0)
        grid.addWidget(self.edit, 1, 0)
        grid.addWidget(self.browse, 1, 1)

        self.setLayout(grid)

    def init_logic(self):
        self.connect(self.browse, SIGNAL('clicked()'), self.pickfolder)
        self.connect(self.originfolder, SIGNAL('clicked()'), self.toggleorginfolder)
        self.connect(self.edit, SIGNAL('textChanged(QString)'), self.setpath)

    def dislogic(self):
        self.disconnect(self.browse, SIGNAL('clicked()'), self.pickfolder)
        self.disconnect(self.originfolder, SIGNAL('clicked()'), self.toggleorginfolder)

    def pickfolder(self):
        #folder = QFileDialog.getExistingDirectory()
        folder = QFileDialog.getExistingDirectory(None, '选择保存目录', '',  QFileDialog.DontUseNativeDialog)
        self.edit.setText(folder)

    def setpath(self, path):
        self.path = self.edit.text()

    def toggleorginfolder(self):
        self.use_origin = self.originfolder.isChecked()
        if self.use_origin:
            self.path = None
            self.edit.setEnabled(False)
            self.browse.setEnabled(False)
        else:
            self.edit.setEnabled(True)
            self.browse.setEnabled(True)
            self.path = self.edit.text()


if __name__ == '__main__':
    app = QApplication(sys.argv)
    gui = UnvpkGui()
    gui.show()
    app.exec_()

